package pers.gxm.visitor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FileFindVisitor extends Visitor{

    private String suffix;
    private List<File> fileList;
    public FileFindVisitor(String suffix){
        this.suffix = suffix;
        fileList = new ArrayList<>();
    }
    @Override
    public void visit(File file) {
//        可以直接用封装好的public boolean endsWith(String suffix)方法
        if(matchFile(file.getName())){
            fileList.add(file);
        }
    }

    @Override
    public void visit(Directory directory) {
        Iterator<Entry> iterator = directory.iterator();
        while(iterator.hasNext()){
            Entry entry = iterator.next();
            entry.accept(this);
        }

    }

    private boolean matchFile(String filename){
        int index = filename.lastIndexOf(".");
//        不是所有文件都有后缀……
        if(index == -1){
            return false;
        }
        String fileSuffix = filename.substring(index);
        return suffix.equals(fileSuffix);
    }

    public Iterator<File> getFoundFiles(){
       return fileList.iterator();
    }
}
